Lesson 1 - Basic code layout

Python source code files will have the file extension py. The following source code can be found in a file called hello.py.


print "hello world"
print "how are you?"


Source code files are saved as text files so they can be opened in any text editor. Each instruction must be on a seperate line. If you wish to annotate code or add a comment you can use the special character "#". The code below demonstrates comments.


# This is a comment! This is ignored by the translator
print "hello world"
print "how are you?"


Text and numbers are differentiated by useing quotation marks. so print "hello world" treats hello world as text. When every you need to add any text you must always surround it with quotation marks. This allows the translator to work out what part is an instruction and which part is just simply text.

Python uses indentation (spaces for the layman!) in order to help seperate code. This is very important as not only does it help with the readability of the code but also code will not run correctly if it is not used. The code block below shows the same code twice. The first one will not work due to the lack of indentation.


# incorrect version
x = 12
if x > 10:
print "x is very big"
print "but is it the biggest"
else:
print "x is too small for me!"

# correct version with indents
x = 12
if x > 10:
    print "x is very big"
    print "but is it the biggest"
else:
    print "x is too small for me!"


Key learning points